package com.umeox.sdk_ring.core

import android.text.TextUtils
import android.text.format.DateFormat
import com.umeox.sdk_ring.UMRingSdk
import java.lang.IllegalArgumentException
import java.text.SimpleDateFormat
import java.util.*

/**
 * 戒指指令生成器
 */
class RingCommandBuilder {

    /**
     * 1.时间下发
     * P01,时间段,12/24小时制
     */
    fun buildP01Command(
        date: Date,
        is24Hour: Boolean?,
        showTime: Boolean,
        timeZone: Double
    ): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(date)
        val show = if (!showTime) {
            "0"
        } else {
            "1"
        }
        //12/24小时制：1,0(默认24)
        val fs: String = if (is24Hour ?: DateFormat.is24HourFormat(UMRingSdk.getApp())) {
            String.format(Locale.ENGLISH, "P01,%s,0,%s,%s", timestamp, show, "$timeZone")
        } else {
            String.format(Locale.ENGLISH, "P01,%s,1,%s,%s", timestamp, show, "$timeZone")
        }
        return fs
    }

    /**
     * 2.获取电量
     * P02,时间段
     */
    fun buildP02Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P02,%s", timestamp)
    }

    /**
     * 3.设置翻转：(0:正，1:反)
     * P03,时间段
     */
    fun buildP03Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P03,%s", timestamp)
    }

    /**
     * 4.寻找设备：操作设置值(0:停止；1:开启)
     * P04,时间段,操作设置值
     */
    fun buildP04Command(enable: Boolean): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        //操作设置值(0:停止；1:开启)
        val fs = if (enable) {
            String.format(Locale.ENGLISH, "P04,%s,%s", timestamp, "1")
        } else {
            String.format(Locale.ENGLISH, "P04,%s,%s", timestamp, "0")
        }
        return fs
    }

    /**
     * 5.接收到设备状态信息
     * P05,时间段
     */
    fun buildP05Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P05,%s", timestamp)
    }

    /**
     * 6.接收到计数信息
     * P06,时间段,tick值
     */
    fun buildP06Command(tick: String): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P06,%s,$tick", timestamp)
    }

    /**
     * 7.实时计数数据接收
     * P07,时间段,tick值
     */
    fun buildP07Command(tick: String): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P07,%s,$tick",
            timestamp
        )
    }

    /**
     * 8.远程关机
     * P08,时间段
     */
    fun buildP08Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P08,%s", timestamp)
    }

    /**
     * 9.祈祷设置
     * P09,时间段,开关,[惯例设置1，惯例设置2，维度，经度，时区]
     */
    fun buildP09Command(
        isOpen: Boolean, calculationMethodPosition: Int, juristicMethodPosition: Int,
        latitude: Double, longitude: Double, timeZone: Double
    ): String {
        val stringBuild = StringBuilder()
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        val fs: String = String.format(Locale.ENGLISH, "P09,%s", timestamp)

        stringBuild.append("$fs,")
        if (isOpen) {
            stringBuild.append("1,")
            stringBuild.append("$calculationMethodPosition,")
            stringBuild.append("$juristicMethodPosition,")
            val internalLatitude = String.format(Locale.US, "%.5f", latitude)
            val internalLongitude = String.format(Locale.US, "%.5f", longitude)
            stringBuild.append("$internalLatitude,$internalLongitude,$timeZone")
        } else {
            stringBuild.append("0")
        }
        return stringBuild.toString()
    }

    /**
     * 10.重启
     * P10,时间段,蓝牙物理地址(12位)
     */
    fun buildP10Command(macAddress: String): String {
        return if (TextUtils.isEmpty(macAddress)) {
            val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
            String.format(Locale.ENGLISH, "P10,%s", timestamp)
        } else {
            val split = macAddress.split(":")
            val result = split.toList().reversed().joinToString("", "", "")
            val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
            String.format(Locale.ENGLISH, "P10,%s,%s", timestamp, result)
        }

    }

    /**
     * 11.诵经提醒设置 //时间范围00:00#23:59 //时间间隔 0,30,60,90 0:停止提醒
     * P11,时间段,时间间隔(分钟),时间范围
     * P11,时间段,0
     */
    fun buildP11Command(
        isOpen: Boolean, startTime: String, endTime: String,
        intervalTime: Int
    ): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        val fs: String = String.format(Locale.ENGLISH, "P11,%s", timestamp)

        val timeInterval = if (!isOpen) {
            "0"
        } else {
            (intervalTime * 60).toString()
        }

        val stringBuilder = StringBuilder()
        stringBuilder.append(fs)
        stringBuilder.append(",")
        stringBuilder.append(timeInterval)

        if (isOpen) {
            stringBuilder.append(",")
            stringBuilder.append("$startTime#$endTime")
        }
        return stringBuilder.toString()
    }

    /**
     * 12.获取设备端所有已存未上传计数数据
     * P12,时间段
     */
    fun buildP12Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P12,%s", timestamp)
    }

    /**
     * 13.获取设备端设置信息
     * P13,时间段
     */
    fun buildP13Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P13,%s", timestamp)
    }

    /**
     * 14.获取设备端相关log信息
     * P14,时间段
     */
    fun buildP14Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P14,%s", timestamp)
    }

    /**
     * 15.亮度设置
     * P15,时间段
     */
    fun buildP15Command(brightness: Int): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P15,%s,$brightness", timestamp)
    }

    /**
     * 16.设置戒指语言
     * P16,时间段
     */
    fun buildP16Command(languageType: Int): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P16,%s,$languageType", timestamp)
    }

    /**
     * 17.设置戒指自定义惯例
     * P17,时间段,自定义ID,fajr_angle,maghrib_is_minutes,maghrib_value,isha_is_minutes,isha_value
     */
    fun buildP17Command(
        fajrAngle: Float, maghribIsMinutes: Boolean,
        maghribValue: Float, ishaIsMinutes: Boolean, ishaValue: Float
    ): String {
        val ishaIsMinutesValue = if (ishaIsMinutes) {
            1
        } else {
            0
        }

        val maghribIsMinutesValue = if (maghribIsMinutes) {
            1
        } else {
            0
        }
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P17,%s,0,%d,%d,%d,%d,%d",
            timestamp,
            (fajrAngle * 10).toInt(),
            maghribIsMinutesValue,
            (maghribValue * 10).toInt(),
            ishaIsMinutesValue,
            (ishaValue * 10).toInt()
        )
    }

    /**
     * 18.特殊祈祷设置
     * P18,时间段,开关
     * ex:P18,时间段,1
     *    P18,时间段,0
     */
    fun buildP18Command(index: Int): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P18,%s,%d",
            timestamp,
            index
        )
    }

    /**
     * P19,时间段,任务开关,目标计数值,当前任务经文值
     * 任务开关:0,1
     * 当前任务经文值
     */
    fun buildP19Command(enable: Boolean, targetNumber: Int, taskId: Int): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        val enableValue = if (enable) {
            1
        } else {
            0
        }
        return String.format(
            Locale.ENGLISH,
            "P19,%s,%d,%d,%d",
            timestamp,
            enableValue,
            targetNumber,
            taskId
        )
    }

    /**
     * 20.获取设备任务信息
     * P20,时间段,tick值
     */
    fun buildP20Command(tick: String): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P20,%s,%s",
            timestamp,
            tick
        )
    }


    /**
     * 21.设置船航模式
     * P21,时间段
     */
    fun buildP21Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P21,%s",
            timestamp
        )
    }

    /**
     * 22.自定义息屏时间设置
     * P22,时间戳,息屏时间
     * 息屏时间(s):10/20/30/40/50/60
     */
    fun buildP22Command(time: Int): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P22,%s,%s",
            timestamp, "$time"
        )
    }

    /**
     * 23.祈祷提醒添加独立开关、偏移时间和提醒时间：
     * 偏移和提醒时间(min): %2d模式，eg:1为01
     * P23,时间戳,晨礼开关#偏移时间#提醒时间:晌礼开关#偏移时间#提醒时间:晡礼开关#偏移时间#提醒时间:昏礼开关#偏移时间#提醒时间:宵礼开关#偏移时间#提醒时间
     */
    fun buildP23Command(configs: Array<Array<Int>>): String {
        if (configs.size != 5) {
            throw IllegalArgumentException("祈祷提醒时刻只有5个时间点，请检查！！！")
        }

        val stringBuilder = StringBuilder()
        val addSymbols: ((value: Int) -> String) = {
            if (it >= 0) {
                "+${
                    String.format(
                        Locale.ENGLISH,
                        "%02d",
                        it
                    )
                }"
            } else {
                "-${
                    String.format(
                        Locale.ENGLISH,
                        "%02d",
                        it
                    )
                }"
            }
        }

        for (config in configs) {
            stringBuilder.append("${config[0]}#")
            stringBuilder.append("${addSymbols(config[1])}#")
            stringBuilder.append("${addSymbols(config[2])}:")
        }

        val sb = stringBuilder.toString()

        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P23,%s,%s",
            timestamp, sb.substring(0, sb.length - 1)
        )
    }

    /**
     * 24.自定义计数提醒
     * P24,时间戳,普通计数33*N模式开关#普通计数100*N模式开关#自定义计数值
     */
    fun buildP24Command(normal33: Boolean, normal100: Boolean, customValue: Int): String {
        val stringBuilder = StringBuilder()
        val addSymbols: ((value: Boolean) -> String) = {
            if (it) {
                "1"
            } else {
                "0"
            }
        }
        stringBuilder.append(addSymbols(normal33))
        stringBuilder.append("#")
        stringBuilder.append(addSymbols(normal100))
        stringBuilder.append("#")
        stringBuilder.append("$customValue")

        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P24,%s,%s",
            timestamp, stringBuilder.toString()
        )
    }

    /**
     * 25.获取祈祷提醒配置信息
     * P25,时间戳
     */
    fun buildP25Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P25,%s",
            timestamp
        )
    }

    /**
     * 26.用户信息设置
     * P26,时间段,age,gender,height,weight,hrMax,hrRest,vo2max
     * age：10 ~ 99
     * gender:0: Female; 1: Male
     * height:100 ~ 220(cm)
     * weight:10 ~ 150 (kg)
     * hrMax:138 ~ 220 bpm //非健康系列,默认200
     * hrRest:40 ~ 100 bpm  //非健康系列,默认50
     * vo2max:大于0   //非健康系列,默认30
     */
    fun buildP26Command(
        age: Int,
        gender: Int,
        height: Int,
        weight: Int,
        hrMax: Int,
        hrRest: Int,
        vo2max: Int
    ): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P26,%s,%d,%d,%d,%d,%d,%d,%d",
            timestamp, age, gender, height, weight, hrMax, hrRest, vo2max
        )
    }

    /**
     * 27.获取当前步数
     * P27,时间段
     */
    fun buildP27Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P27,%s",
            timestamp
        )
    }

    /**
     * 28.获取睡眠信息
     * P28,时间段
     */
    fun buildP28Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P28,%s",
            timestamp
        )
    }

    /**
     * 29.获取所有时间段计步信息
     * P29,时间段
     */
    fun buildP29Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P29,%s",
            timestamp
        )
    }

    /**
     * 30.pkey读写操作
     * P30,时间段,读写标志,pkey字符串
     * //读写标志：0读取；1写入；
     * //pkey字符串:64字节
     * //P30,时间段,0
     * //P30,时间段,1,pYVRH2eMRmy9AQ8zMM/Wk8BTCDk879yxlAuqcaddV5PsDC0t0Xdz0dhE/3v4J6ww
     */
    fun buildP30Command(write: Boolean, pkey: String): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return if (write) {
            String.format(
                Locale.ENGLISH,
                "P30,%s,1,%s",
                timestamp, pkey
            )
        } else {
            String.format(
                Locale.ENGLISH,
                "P30,%s,0",
                timestamp
            )
        }
    }

    fun buildP31Command(light: Boolean): String {
        val result = if (light) {
            "1"
        } else {
            "0"
        }
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P31,%s,%s",
            timestamp, result
        )
    }

    fun buildP32Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P32,%s", timestamp
        )
    }

    fun setTimeShowType(type: Int): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(
            Locale.ENGLISH,
            "P33,%s,%d", timestamp, type
        )
    }

    /**
     * 34.朝拜计数信息获取
     * P34,时间段,tick值
     */
    fun buildP34Command(tick: String): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P34,%s,%s", timestamp, tick)
    }

    /**
     * 35.实时朝拜计数接收
     * P35,时间段
     */
    fun buildP35Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P35,%s", timestamp)
    }

    /**
     * 36.led灯时间及亮度设定
     * //显示时间：秒（5-300）
     * //亮度值：（5-255）
     * P36,时间段,显示时间,亮度值
     */
    fun buildP36Command(lightTime: Int, light: Int): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P36,%s,%d,%d", timestamp, lightTime, light)
    }

    /**
     * 37.设备信息获取
     * P37,时间段
     */
    fun buildP37Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P37,%s", timestamp)
    }

    /**
     * 38.设备红外测试
     * P38,时间段,测试开关（0：打开，1：关闭）
     */
    fun buildP38Command(enable: Boolean): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        val flag = if (enable) {
            0
        } else {
            1
        }
        return String.format(Locale.ENGLISH, "P38,%s,%d", timestamp, flag)
    }

    /**
     * 39.设备雷达测试
     * P39,时间段,测试开关（0：打开，1：关闭）
     */
    fun buildP39Command(enable: Boolean): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        val flag = if (enable) {
            0
        } else {
            1
        }
        return String.format(Locale.ENGLISH, "P39,%s,%d", timestamp, flag)
    }

    fun buildP40Command(): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P40,%s", timestamp)
    }

    fun buildP41Command(index: Int, number: Int): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        return String.format(Locale.ENGLISH, "P41,%s,%d,%d", timestamp, index, number)
    }

    fun buildP42Command(enable: Boolean): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        val flag = if (enable) {
            0
        } else {
            1
        }
        return String.format(Locale.ENGLISH, "P42,%s,%d", timestamp, flag)
    }

    fun buildP43Command(): String {
        return String.format(Locale.ENGLISH, "P43")
    }

    fun buildP44Command(): String {
        return String.format(Locale.ENGLISH, "P44")
    }

    fun buildP45Command(): String {
        return String.format(Locale.ENGLISH, "P45")
    }

    fun buildP46Command(): String {
        return String.format(Locale.ENGLISH, "P46")
    }

    fun buildP47Command(audio1Enable: Boolean, audio2Enable: Boolean): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        val audio1Flag = if (audio1Enable) {
            1
        } else {
            0
        }
        val audio2Flag = if (audio2Enable) {
            1
        } else {
            0
        }
        return String.format(Locale.ENGLISH, "P47,%s,%d,%d", timestamp, audio1Flag, audio2Flag)
    }

    fun buildP51Command(audioEnable: Boolean): String {
        val timestamp = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).format(Date())
        val audioEnableFlag = if (audioEnable) {
            1
        } else {
            0
        }
        return String.format(Locale.ENGLISH, "P51,%s,%d", timestamp, audioEnableFlag)
    }
}